import React, { createContext, useState, useContext, useEffect, useCallback, useRef } from 'react';
import { MessageService } from './services/MessageService';
import { useAuth } from '../auth/AuthContext';

interface MessagesContextType {
  messages: any[];
  unreadCount: number;
  isLoading: boolean;
  sendMessage: (message: any) => Promise<any>;
  markAsRead: (messageId: number) => Promise<void>;
  deleteMessage: (userId: string) => Promise<void>;
  refreshMessages: () => Promise<void>;
}

const MessagesContext = createContext<MessagesContextType>({
  messages: [],
  unreadCount: 0,
  isLoading: false,
  sendMessage: async () => ({}),
  markAsRead: async () => {},
  deleteMessage: async () => {},
  refreshMessages: async () => {},
});

// 创建防抖函数
const useDebounce = (fn: Function, delay: number) => {
  const timer = useRef<NodeJS.Timeout | null>(null);
  
  return useCallback((...args: any[]) => {
    if (timer.current) {
      clearTimeout(timer.current);
    }
    timer.current = setTimeout(() => {
      fn(...args);
    }, delay);
  }, [fn, delay]);
};

export const MessagesProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [messages, setMessages] = useState<any[]>([]);
  const [unreadCount, setUnreadCount] = useState<number>(0);
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const { user } = useAuth();
  const isInitialMount = useRef(true);
  
  // 使用useCallback优化函数，避免不必要的重新创建
  const fetchMessages = useCallback(async () => {
    if (!user) return;
    
    try {
      setIsLoading(true);
      const data = await MessageService.getConversations();
      if (data) {
        setMessages(data);
      }
    } catch (error) {
      console.error('获取消息列表失败:', error);
    } finally {
      setIsLoading(false);
    }
  }, [user]);
  
  const fetchUnreadCount = useCallback(async () => {
    if (!user) return;
    
    try {
      const count = await MessageService.getUnreadMessageCount();
      setUnreadCount(count);
    } catch (error) {
      console.error('获取未读消息数量失败:', error);
    }
  }, [user]);
  
  // 组件挂载时获取消息列表和未读消息数量
  useEffect(() => {
    if (isInitialMount.current && user) {
      isInitialMount.current = false;
      fetchMessages();
      fetchUnreadCount();
    }
  }, [user, fetchMessages, fetchUnreadCount]);
  
  // 使用useCallback优化sendMessage函数
  const sendMessage = useCallback(async (message: any) => {
    if (!user) throw new Error('用户未登录');
    
    try {
      const sentMessage = await MessageService.sendMessage(message);
      
      // 更新消息列表
      setMessages(prevMessages => {
        // 检查是否已存在该对话的消息
        const existingMessageIndex = prevMessages.findIndex(
          msg => (msg.senderId === user.id && msg.receiverId === message.receiverId) ||
                (msg.receiverId === user.id && msg.senderId === message.receiverId)
        );
        
        if (existingMessageIndex >= 0) {
          // 如果存在，更新现有消息列表
          const updatedMessages = [...prevMessages];
          updatedMessages[existingMessageIndex] = sentMessage;
          return updatedMessages;
        } else {
          // 如果不存在，添加新消息
          return [...prevMessages, sentMessage];
        }
      });
      
      return sentMessage;
    } catch (error) {
      console.error('发送消息失败:', error);
      throw error;
    }
  }, [user]);
  
  // 使用useCallback优化markAsRead函数
  const markAsRead = useCallback(async (messageId: number) => {
    if (!user) return;
    
    try {
      const message = messages.find(msg => msg.id === messageId);
      if (!message) return;
      
      const senderId = message.senderId;
      if (message.receiverId !== user.id) return; // 只有接收者才能标记为已读
      
      await MessageService.markMessagesAsRead(senderId);
      
      // 更新消息状态
      setMessages(prevMessages =>
        prevMessages.map(msg =>
          msg.senderId === senderId && msg.receiverId === user.id
            ? { ...msg, isRead: true }
            : msg
        )
      );
      
      // 更新未读消息数量
      fetchUnreadCount();
    } catch (error) {
      console.error('标记消息为已读失败:', error);
    }
  }, [messages, user, fetchUnreadCount]);
  
  // 使用useCallback优化deleteMessage函数
  const deleteMessage = useCallback(async (userId: string) => {
    if (!user) return;
    
    try {
      await MessageService.deleteMessage(userId);
      
      // 从列表中移除与该用户的所有对话
      setMessages(prevMessages =>
        prevMessages.filter(msg =>
          !(msg.senderId === userId && msg.receiverId === user.id) &&
          !(msg.senderId === user.id && msg.receiverId === userId)
        )
      );
      
      // 更新未读消息数量
      fetchUnreadCount();
    } catch (error) {
      console.error('删除消息失败:', error);
      throw error;
    }
  }, [user, fetchUnreadCount]);
  
  // 使用useCallback和防抖优化refreshMessages函数
  const refreshMessages = useDebounce(async () => {
    await fetchMessages();
    await fetchUnreadCount();
  }, 300);
  
  return (
    <MessagesContext.Provider
      value={{
        messages,
        unreadCount,
        isLoading,
        sendMessage,
        markAsRead,
        deleteMessage,
        refreshMessages,
      }}
    >
      {children}
    </MessagesContext.Provider>
  );
};

export const useMessages = () => useContext(MessagesContext);